package base62

import (
	"math"
	"strings"
)

//62进制转换模块

//0-9
//a-z
//A-Z

// 十进制转换位62进制
const base62Str = `0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ`

//为了避免被别人恶意请求，我们可以将上面字符串打乱

//以下是合法的
//var a string = "asdiuifh"
//fmt.Println(a[3])

func IntToBase62(num uint64) string {
	if num == 0 {
		return string(base62Str[0])
	}
	s := []byte{}
	for num > 0 {
		mod := num % 62
		num = num / 62
		s = append(s, base62Str[mod])
	}
	//最后把数据反转
	return reverse(s)
}

func Base62ToInt(s string) (seq uint64) {
	bl := []byte(s)
	rev := reverse(bl)
	bl = []byte(rev)
	for idx, b := range bl {
		base := math.Pow(62, float64(idx))
		seq += uint64(strings.Index(base62Str, string(b))) * uint64(base)
	}
	return seq
}

func reverse(s []byte) string {
	for i, j := 0, len(s)-1; i < len(s)/2; i, j = i+1, j-1 {
		s[i], s[j] = s[j], s[i]
	}
	return string(s)
}
